<?php
namespace backend\controllers;

use backend;
use backend\base\BaseService;
use common\base_models\kds\AdminRolePermission;
use Yii;
use backend\base\BaseController;
use backend\models\AdminModel;
use backend\models\AreaModel;
use backend\services\AdminService;
use backend\models\SystemLoginLogModel;

/**
 * Site controller
 */
class SiteController extends BaseController
{
    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        // echo Yii::$app->controller->id.'==='.Yii::$app->controller->action->id;
        // echo 11;die;
        if(Yii::$app->user->isGuest){
            return $this->redirect(array('site/login'));
        }else{
            return $this->redirect(array('site/demo'));
        }
    }

    /**
     * 登录
     * @return array|string
     */
    public function actionLogin()
    {
        $data = parent::parseData($this->body);
        if (!empty($data)) {
            if (preg_match('/1[13456789]{1}\d{9}/', $data['username'])) { //手机号
                $condition = ['and',['mobile' => $data['username']],['status'=>1]];
                $data['mobile'] = $data['username'];
            } else if (preg_match('/YS|ys|Ys|yS|SH|sh|Sh|sH/', $data['username']) && $data['username'] != 'yisheng') {  //工号
                $condition = ['and',['job_number' => $data['username']],['status'=>1]];
                $data['job_number'] = $data['username'];
            } else { //管理员姓名登陆
                $condition = ['and',['name' => $data['username']],['status'=>1]];
                $data['name'] = $data['username'];
            }
            $platformUser = AdminModel::find()->where($condition)->one();
            if($platformUser){
                $model = new AdminModel(['scenario' => 'login']);
                if ($model->load($data, '') && $model->validate()) {//电话登录
                    if ($admin = $model->loginValidate()) {  //查找到并且密码匹配，登录
                        Yii::$app->user->login($admin, 3600 * 2);
                        SystemLoginLogModel::addLog(1);
                        return self::ReturnData('operate_success_login');
                    }
                }
            }
            SystemLoginLogModel::addLog(0);
            return self::ReturnData('login_error');//数据库后端字段验证错误
        } else {
            if(!Yii::$app->user->isGuest){
                return $this->redirect(array('site/demo'));
            }
            $this->layout = false;
            return $this->render('login', ['csrf' => Yii::$app->request->csrfToken]);
        }
    }

    /*
     * 忘记密码
     * @return array
     */
    public function actionForgetPass()
    {
        $this->layout = false;
        $data = parent::parseData($this->body);
        if (!empty($data)) {
            if (Yii::$app->cache->get('forgetpass'.$data['mobile']) == $data['code_num']) {//验证码成功
                $model = new AdminModel();
                $userInfo = $model->getByMobile(['mobile' => $data['password']]);
                //判断新密码与旧密码是否一致
                $oldAndNew = Yii::$app->security->validatePassword($data['password'].$userInfo->create_time);
                if(!empty($oldAndNew)){
                    return json_encode(parent::ajaxReturn('new_old_pass_error', []));
                }
                //修改密码
                $re = AdminService::editPassword($data['password'], $data['mobile']);
                if ($re === -1) {
                    return json_encode(parent::ajaxReturn('mobile_miss_error', []));//手机号不存在
                } elseif ($re === true) {
                    return json_encode(parent::ajaxReturn('pass_operate_success', []));//密码修改成功
                } else {
                    return json_encode(parent::ajaxReturn('update_pass_error', []));//密码修改失败
                }
            }
            return json_encode(parent::ajaxReturn('code_check_error', []));//电话验证码不匹配
        } else {
            return $this->render('forget-pass');
        }
    }

    /*
     * ajax方法发送验证码
     * @return array
     */
    public function actionSendNote()
    {
        $data = parent::parseData($this->body);
        if (empty($data['mobile'])) {//参数错误
            return json_encode(parent::ajaxReturn('param_error', []));
        }
        $platformUser = AdminModel::find()->where(['mobile' => $data['mobile']])->one();
        if (!$platformUser) {//电话不存在
            return json_encode(parent::ajaxReturn('mobile_miss_error', []));
        }
        if (!empty(Yii::$app->cache->get('forgetpass'.$data['mobile']))) {//验证码未过期
            return json_encode(parent::ajaxReturn('code_send_error', []));//提示已经发过了
        }
        $result = BaseService::sendMessage($data['mobile'],Yii::$app->params['validateMessage']);//发送验证码
        echo '<pre>';
        print_r($result);die;
        $pwd = rand(100000,999999);
        Yii::$app->cache->set('forgetpass'.$data['mobile'], $pwd,180);//缓存验证码
        return json_encode(parent::ajaxReturn('code_send_success', []));//发送成功
    }

    /*
     * 用旧密码修改密码
     * @return array
     */
    public function actionUpdatePassword()
    {
        $data = parent::parseData($this->body);
        if (empty($data)) {
            return $this->render('update');
        } else {
            $oldpassword = $data['oldPassword'];
            $password1   = $data['kdsLoginPwd'];
            if (!$oldpassword || !$password1) {
                return json_encode(parent::ajaxReturn('param_error', []));//参数错误
            }
            $re = AdminService::editPassword($password1, Yii::$app->user->identity->id, "", $oldpassword, 2);
            if ($re === -1) {
                return json_encode(parent::ajaxReturn('old_pass_error', []));//原密码错误
            } else if ($re === true) {
                return json_encode(parent::ajaxReturn('pass_operate_success', []));//密码修改成功
            } else {
                return json_encode(parent::ajaxReturn('update_pass_error', []));//密码修改失败
            }
        }
    }

    /*
     * 登出
     * @return array
     */
    public function actionLogout()
    {
        if (Yii::$app->user->logout()) {
            return $this->redirect(array('site/login'));
        }
    }

    /*
     * 默认进入首页
     */
    public function actionDemo()
    {
        Yii::$app->layout = 'main';
        return $this->render('demo');
    }

    /**
     * 权限不足页
     */
    public function actionAuthError(){
        return $this->render('auth-error');
    }

    /**
     * 共用修改排序值
     */
    public function actionSortEdit(){
        $data = Yii::$app->request->post();
        $modelname = 'backend\models\\'.$data['model'];
        $model = $modelname::findOne(['id'=>$data['id']]);
        if($model){
            $model->sort = (int)$data['sort'];
            if($model->save()){
                return json_encode(parent::ajaxReturn('operate_success_edit'));
            }
        }
        return json_encode(parent::ajaxReturn('edit_error'));
    }

    /**
     * 获取某代理商下的区域列表
     * @return string
     * @throws \yii\base\Exception
     */
    public function actionGetAgentArea(){
        $list = [];
        $agent_id = $this->post('agent_id');
        if($agent_id){
            $list = backend\models\AgentAreaModel::getMyCountryList($agent_id);
        }
        return json_encode(parent::ajaxReturn('request_success', $list));
    }

    /**
     * 获取地区
     * @return string
     * @throws \yii\base\Exception
     */
    public function actionGetarea()
    {
        $id = (int)$this->body['id'];
        if(isset($this->body['sign']) && $this->body['sign'] == 1){
            $list = (new AreaModel())->getNoSignArea($id);
        }else{
            $list = (new AreaModel())->getArea($id);
        }
        return json_encode(parent::ajaxReturn('request_success', $list));
    }

    /**
     * 获取视频上传凭证
     * @param string $dir
     * @return string
     */
    public function actionUploadVideo(){
        $data = $this->body;
        $response = CourseVideoModel::createUploadVideo($data);
        return json_encode(parent::ajaxReturn('request_success', $response));
    }

    /**
     * 刷新视频上传凭证
     * @param string $dir
     * @return string
     */
    public function actionRefreshUploadVideo(){
        $data = $this->body;
        if(empty($data['video_id'])){
            return json_encode(parent::ajaxReturn('param_error'));
        }
        $response = CourseVideoModel::refreshUploadVideo($data['video_id']);
        return json_encode(parent::ajaxReturn('request_success', $response));
    }


    /**
     * 获取视频播放凭证
     * @param string $dir
     * @return string
     */
    public function actionGetVideoPlayAuth(){
        try{
            $data = parent::parseData($this->body);
            if(!empty($data['video_id'])){
                $response = CourseVideoModel::getVideoPlayAuth($data['video_id']);
                return json_encode(parent::ajaxReturn('request_success', $response));
            }
            return json_encode(parent::ajaxReturn('param_error'));
        }catch(\Exception $e){
            //return json_encode(parent::ajaxReturn('param_error'));
        }
    }

    /**
     * 获取oss上传参数
     * @return string
     * @throws \yii\base\Exception
     */
    public function actionGetOssUpload(){
        $response = backend\models\OssModel::getOssUpload();
        return json_encode(parent::ajaxReturn('request_success', json_decode($response)));
    }

    /**
     * 批量上传视频
     * @return string
     */
    public function actionKdsUploadVideo()
    {
        $this->layout = false;
        return $this->render('kds-upload-video');
    }
}
